<template>
	<div class="orbit-designer">
		<div class="orbit-designer-header">
			<p class="description">通过设置轨道六根数参数来设计自定义卫星轨道</p>
		</div>

		<div class="orbit-designer-content">
			<!-- 轨道参数表单 -->
			<div class="parameters-section">
				<div class="preview-controls">
					<el-switch
						v-model="enablePreview"
						active-text="实时预览"
						inactive-text="关闭预览"
						@change="handlePreviewToggle"
					/>
					<span v-if="enablePreview && previewOrbitEntity" class="preview-status">
						<el-icon color="#67C23A"><CircleCheckFilled /></el-icon>
						预览轨道已显示
					</span>
				</div>
				<OrbitParametersForm
					:orbit-params="currentOrbitParams"
					@update:orbit-params="handleParamChange"
					@apply-template="handleApplyTemplate"
					@real-time-update="handleRealTimeUpdate"
					@reference-system-toggle="handleReferenceSystemToggle"
					@earth-transparency-change="handleEarthTransparencyChange"
					:enable-real-time="enablePreview"
				/>
			</div>

			<!-- 轨道信息显示 -->
			<div class="orbit-info-section">
				<div class="orbit-info-card">
					<h4>轨道信息</h4>
					<div class="info-grid">
						<div class="info-item">
							<span class="label">轨道周期:</span>
							<span class="value">{{ formatTime(orbitInfo.period) }}</span>
						</div>
						<div class="info-item">
							<span class="label">近地点高度:</span>
							<span class="value">{{ orbitInfo.perigeeAltitude.toFixed(2) }} km</span>
						</div>
						<div class="info-item">
							<span class="label">远地点高度:</span>
							<span class="value">{{ orbitInfo.apogeeAltitude.toFixed(2) }} km</span>
						</div>
						<div class="info-item">
							<span class="label">轨道类型:</span>
							<span class="value">{{ orbitInfo.orbitType }}</span>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { CircleCheckFilled } from '@element-plus/icons-vue';
import OrbitParametersForm from './OrbitParametersForm.vue';
import CustomSatelliteEntity from '@/utils/CustomSatelliteEntity.js';
import * as Cesium from 'cesium';

// Props
const props = defineProps({
	cesiumViewer: {
		type: Object,
		required: true
	}
});

// 当前轨道参数（默认太阳同步轨道）
const currentOrbitParams = reactive({
	semiMajorAxis: 7178, // 半长轴 (km) (~800km高度)
	eccentricity: 0.001, // 偏心率
	inclination: 98.2, // 轨道倾角 (度)
	raan: 0.0, // 升交点赤经 (度)
	argumentOfPerigee: 0.0, // 近地点幅角 (度)
	meanAnomaly: 0.0 // 平近点角 (度)
});

// 实时预览轨道实体
const previewOrbitEntity = ref(null);

// 预览开关
const enablePreview = ref(true);

// 坐标系和参考平面显示状态
const showReferenceSystem = ref(false);
const referenceSystemEntities = ref([]);
const latLonGridLayer = ref(null);

// 轨道信息计算
const orbitInfo = computed(() => {
	const params = currentOrbitParams;
	const earthRadius = 6371; // 地球半径 (km)
	const mu = 398600.4418; // 地球引力参数 (km³/s²)

	// 计算轨道周期 (秒)
	const period = 2 * Math.PI * Math.sqrt(Math.pow(params.semiMajorAxis, 3) / mu);

	// 计算近地点和远地点高度
	const perigeeAltitude = params.semiMajorAxis * (1 - params.eccentricity) - earthRadius;
	const apogeeAltitude = params.semiMajorAxis * (1 + params.eccentricity) - earthRadius;

	// 判断轨道类型
	let orbitType = 'LEO';
	if (perigeeAltitude > 2000) {
		orbitType = 'MEO';
	}
	if (perigeeAltitude > 35786) {
		orbitType = 'GEO';
	}
	if (params.eccentricity > 0.25) {
		orbitType = 'HEO';
	}

	return {
		period,
		perigeeAltitude,
		apogeeAltitude,
		orbitType
	};
});

// 处理参数变化
const handleParamChange = (newParams) => {
	Object.assign(currentOrbitParams, newParams);
};

// 应用轨道模板
const handleApplyTemplate = (template) => {
	Object.assign(currentOrbitParams, template.params);
	ElMessage.success(`已应用 ${template.name} 轨道模板`);
};

// 处理预览开关切换
const handlePreviewToggle = (enabled) => {
	if (!enabled && previewOrbitEntity.value && props.cesiumViewer) {
		props.cesiumViewer.entities.remove(previewOrbitEntity.value);
		previewOrbitEntity.value = null;
	} else if (enabled) {
		// 重新创建预览轨道
		handleRealTimeUpdate(currentOrbitParams);
	}
};

// 处理实时参数更新
const handleRealTimeUpdate = (params) => {
	if (!props.cesiumViewer || !enablePreview.value) return;

	try {
		// 移除之前的预览轨道和已添加的近/远地点标记
		if (previewOrbitEntity.value) {
			const old = previewOrbitEntity.value;
			if (old.perigeePoint) {
				props.cesiumViewer.entities.remove(old.perigeePoint);
			}
			if (old.apogeePoint) {
				props.cesiumViewer.entities.remove(old.apogeePoint);
			}
			if (old.apsisLine) {
				props.cesiumViewer.entities.remove(old.apsisLine);
			}
			props.cesiumViewer.entities.remove(old);
			previewOrbitEntity.value = null;
		}

		// 创建预览轨道（指定红色）
		// 将开始时间锚定到当前viewer时间，避免时间轴不一致导致很快越界
		const viewerStartTime = props.cesiumViewer
			? Cesium.JulianDate.toDate(props.cesiumViewer.clock.currentTime).getTime()
			: Date.now();
		// 扩展可视时长：至少24小时，最多48小时，或不小于约12个轨道周期，避免很快消失
		const minDuration = 24 * 3600;
		const maxDuration = 48 * 3600;
		const durationSeconds = Math.min(Math.max(orbitInfo.value.period * 12, minDuration), maxDuration);
		const previewSatellite = CustomSatelliteEntity.fromOrbitElements('卫星', params, {
			startTime: viewerStartTime,
			totalSeconds: durationSeconds,
			stepSeconds: 30,
			// 路径窗口拉满以覆盖整段可用时间
			leadTime: durationSeconds,
			trailTime: durationSeconds,
			color: Cesium.Color.RED.withAlpha(0.6) // 直接在创建时指定红色
		});

		const previewEntity = previewSatellite.createSatelliteEntity();

		// 确保轨道路径为红色
		if (previewEntity.path) {
			previewEntity.path.material = Cesium.Color.RED.withAlpha(0.6);
			previewEntity.path.width = 1;
			// 确保路径可见
			previewEntity.path.show = true;
		}
		// 确保卫星点也为蓝色
		if (previewEntity.point) {
			previewEntity.point.color = Cesium.Color.BLUE.withAlpha(0.9);
			previewEntity.point.pixelSize = 8; // 增大点的大小，使其更容易看到
		}

		previewOrbitEntity.value = props.cesiumViewer.entities.add(previewEntity);

		// 添加近地点和远地点标记
		addApsisPoints(params);

		// 如果坐标系正在显示，更新近地点远地点连线
		if (showReferenceSystem.value) {
			createReferenceSystem();
		}

		// 自动定位到轨道 - 已禁用，避免不必要的视角调整
		// props.cesiumViewer.zoomTo(previewOrbitEntity.value);
		console.log('预览轨道已创建:', previewEntity);
	} catch (error) {
		console.warn('实时预览更新失败:', error);
	}
};

// 处理坐标系显示切换
const handleReferenceSystemToggle = (show) => {
	showReferenceSystem.value = show;
	if (show) {
		createReferenceSystem();
	} else {
		removeReferenceSystem();
	}
};

// 处理地球透明度变化
const handleEarthTransparencyChange = (transparency) => {
	if (!props.cesiumViewer) return;
	
	// 更新地球透明度
	props.cesiumViewer.scene.globe.translucency.enabled = true;
	props.cesiumViewer.scene.globe.translucency.frontFaceAlpha = transparency;
	props.cesiumViewer.scene.globe.translucency.backFaceAlpha = transparency;
};

// 创建坐标系和参考平面
const createReferenceSystem = () => {
	if (!props.cesiumViewer) return;

	// 清除之前的坐标系
	removeReferenceSystem();

	const entities = props.cesiumViewer.entities;

	// 1. 创建地球XYZ坐标轴
	createCoordinateAxes(entities);

	// 2. 创建赤道平面
	createEquatorialPlane(entities);

	// 2.5 创建黄道平面（与赤道面相同大小）
	createEclipticPlane(entities);

	// 2.6 创建春分点/秋分点轴（沿黄道与赤道交线，即±X方向）
	createEquinoxAxes(entities);

	// 2.7 创建天球
	createCelestialSphere(entities);

	// 2.8 创建太阳在黄道面的投影
	createSunProjection(entities);

	// 2.9 创建轨道面
	if (previewOrbitEntity.value) {
		createOrbitPlane(entities);
	}

	// 3. 创建经纬度网格（使用内置 GridImageryProvider）
	createLatLonGridLayer();

	// 4. 如果有轨道，创建近地点远地点连线
	if (previewOrbitEntity.value) {
		createApsisLine(entities);
	}
};

// 创建坐标轴
const createCoordinateAxes = (entities) => {
	const earthRadius = 6371000; // 地球半径
	const axisLength = earthRadius * 5; // 与春分点轴长度保持一致
	const axisWidth = 1; // 设置线宽为1

	// 使用笛卡尔坐标系创建坐标轴，确保Z轴为直线

	// X轴 (红色) - 沿X方向，从地心开始
	const xAxisPositions = [new Cesium.Cartesian3(1, 0, 0), new Cesium.Cartesian3(axisLength, 0, 0)];

	const xAxis = entities.add({
		name: 'X轴',
		polyline: {
			positions: xAxisPositions,
			width: axisWidth,
			material: Cesium.Color.RED.withAlpha(0.9),
			clampToGround: false
		}
	});
	referenceSystemEntities.value.push(xAxis);

	// Y轴 (绿色) - 沿Y方向，从地心开始
	const yAxisPositions = [new Cesium.Cartesian3(0, 1, 0), new Cesium.Cartesian3(0, axisLength, 0)];

	const yAxis = entities.add({
		name: 'Y轴',
		polyline: {
			positions: yAxisPositions,
			width: axisWidth,
			material: Cesium.Color.GREEN.withAlpha(0.9),
			clampToGround: false
		}
	});
	referenceSystemEntities.value.push(yAxis);

	// Z轴 (蓝色) - 沿Z方向，从地心开始向上
	const zAxisPositions = [new Cesium.Cartesian3(0, 0, 1), new Cesium.Cartesian3(0, 0, axisLength)];

	const zAxis = entities.add({
		name: 'Z轴',
		polyline: {
			positions: zAxisPositions,
			width: axisWidth,
			material: Cesium.Color.BLUE.withAlpha(0.9),
			clampToGround: false
		}
	});
	referenceSystemEntities.value.push(zAxis);

	// 添加坐标轴箭头（圆锥）
	const arrowLength = 800000; // 箭头长度
	const arrowRadius = 200000; // 箭头底部半径

	// X轴箭头
	const xArrow = entities.add({
		name: 'X轴箭头',
		position: new Cesium.Cartesian3(axisLength - arrowLength / 2, 0, 0),
		orientation: Cesium.Transforms.headingPitchRollQuaternion(
			new Cesium.Cartesian3(axisLength - arrowLength / 2, 0, 0),
			new Cesium.HeadingPitchRoll(0, 0, 0)
		),
		cylinder: {
			length: arrowLength,
			topRadius: 0,
			bottomRadius: arrowRadius,
			material: Cesium.Color.RED.withAlpha(0.9)
		}
	});
	referenceSystemEntities.value.push(xArrow);

	// Y轴箭头
	const yArrow = entities.add({
		name: 'Y轴箭头',
		position: new Cesium.Cartesian3(0, axisLength - arrowLength / 2, 0),
		orientation: Cesium.Transforms.headingPitchRollQuaternion(
			new Cesium.Cartesian3(0, axisLength - arrowLength / 2, 0),
			new Cesium.HeadingPitchRoll(0, 0, 0)
		),
		cylinder: {
			length: arrowLength,
			topRadius: 0,
			bottomRadius: arrowRadius,
			material: Cesium.Color.GREEN.withAlpha(0.9)
		}
	});
	referenceSystemEntities.value.push(yArrow);

	// Z轴箭头
	const zArrow = entities.add({
		name: 'Z轴箭头',
		position: new Cesium.Cartesian3(0, 0, axisLength - arrowLength / 2),
		cylinder: {
			length: arrowLength,
			topRadius: 0,
			bottomRadius: arrowRadius,
			material: Cesium.Color.BLUE.withAlpha(0.9)
		}
	});
	referenceSystemEntities.value.push(zArrow);

	// 添加坐标轴标签
	const labelOffset = 500000; // 标签偏移距离

	// X轴标签
	const xLabel = entities.add({
		name: 'X轴标签',
		position: new Cesium.Cartesian3(axisLength + labelOffset, 0, 0),
		label: {
			text: 'X',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.RED,
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -20)
		}
	});
	referenceSystemEntities.value.push(xLabel);

	// Y轴标签
	const yLabel = entities.add({
		name: 'Y轴标签',
		position: new Cesium.Cartesian3(0, axisLength + labelOffset, 0),
		label: {
			text: 'Y',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.GREEN,
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -20)
		}
	});
	referenceSystemEntities.value.push(yLabel);

	// Z轴标签
	const zLabel = entities.add({
		name: 'Z轴标签',
		position: new Cesium.Cartesian3(0, 0, axisLength + labelOffset),
		label: {
			text: 'Z',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.BLUE,
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -20)
		}
	});
	referenceSystemEntities.value.push(zLabel);
};

// 创建赤道平面
const createEquatorialPlane = (entities) => {
	const earthRadius = 6371000; // 地球半径 (米)
	const planeRadius = earthRadius * 5; // 圆盘半径
	const height = 0; // 平面高度：z = 200 km，避免被地球遮挡

	// 生成圆形多边形顶点（位于全球 XY 平面 z = height）
	const segments = 180;
	const circlePositions = [];
	for (let i = 0; i < segments; i++) {
		const angle = (i / segments) * Math.PI * 2;
		circlePositions.push(new Cesium.Cartesian3(planeRadius * Math.cos(angle), planeRadius * Math.sin(angle), height));
	}

	// 填充圆盘
	const equatorialFill = entities.add({
		name: '赤道平面',
		polygon: {
			hierarchy: new Cesium.PolygonHierarchy(circlePositions),
			perPositionHeight: true,
			material: Cesium.Color.GREEN.withAlpha(0.2)
		}
	});
	referenceSystemEntities.value.push(equatorialFill);

	// 轮廓圆环
	const equatorialOutline = entities.add({
		name: '赤道平面轮廓',
		polyline: {
			positions: [...circlePositions, circlePositions[0]],
			width: 1,
			material: Cesium.Color.GREEN.withAlpha(0.3),
			clampToGround: false
		}
	});
	referenceSystemEntities.value.push(equatorialOutline);

	// 添加赤道面标签
	// 相对于X轴标签偏移10度
	const labelAngleOffset = Cesium.Math.toRadians(10); // 10度偏移
	const labelRadius = planeRadius * 1;
	const equatorialLabel = entities.add({
		name: '赤道面标签',
		position: new Cesium.Cartesian3(
			labelRadius * Math.cos(labelAngleOffset),
			labelRadius * Math.sin(labelAngleOffset),
			0
		), // 相对于X轴偏移10度
		label: {
			text: '赤道面',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.WHITE, // 改为白色
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -20)
		}
	});
	referenceSystemEntities.value.push(equatorialLabel);
};

// 新增：创建黄道平面（按赤道面的大小）
const createEclipticPlane = (entities) => {
	const earthRadius = 6371000; // 地球半径 (米)
	const planeRadius = earthRadius * 5; // 使用与赤道面相同的半径

	// 在 ICRF 下构造黄道面圆环（由ICRF赤道面绕 +X 轴按黄赤交角旋转）
	const obliquity = Cesium.Math.toRadians(23.439281);
	const cosE = Math.cos(obliquity);
	const sinE = Math.sin(obliquity);
	const segments = 180;
	const ringIcrf = [];
	for (let i = 0; i < segments; i++) {
		const angle = (i / segments) * Math.PI * 2;
		const x = planeRadius * Math.cos(angle);
		const y = planeRadius * Math.sin(angle);
		const z = 0.0;
		const yR = y * cosE - z * sinE;
		const zR = y * sinE + z * cosE;
		ringIcrf.push(new Cesium.Cartesian3(x, yR, zR));
	}

	const transformRingToFixed = (time) => {
		let m = Cesium.Transforms.computeIcrfToFixedMatrix(time);
		if (!m) m = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
		const out = new Array(ringIcrf.length);
		for (let i = 0; i < ringIcrf.length; i++) {
			out[i] = Cesium.Matrix3.multiplyByVector(m, ringIcrf[i], new Cesium.Cartesian3());
		}
		return out;
	};

	const hierarchyProperty = new Cesium.CallbackProperty((time) => {
		const positions = transformRingToFixed(time);
		return new Cesium.PolygonHierarchy(positions);
	}, false);

	const outlinePositionsProperty = new Cesium.CallbackProperty((time) => {
		const positions = transformRingToFixed(time);
		return [...positions, positions[0]];
	}, false);

	const eclipticFill = entities.add({
		name: '黄道面',
		polygon: {
			hierarchy: hierarchyProperty,
			perPositionHeight: true,
			material: Cesium.Color.GOLD.withAlpha(0.18)
		}
	});
	referenceSystemEntities.value.push(eclipticFill);

	const eclipticOutline = entities.add({
		name: '黄道面轮廓',
		polyline: {
			positions: outlinePositionsProperty,
			width: 1,
			material: Cesium.Color.GOLD.withAlpha(0.5),
			clampToGround: false
		}
	});
	referenceSystemEntities.value.push(eclipticOutline);

	// 添加黄道面标签
	const eclipticLabelPos = new Cesium.CallbackProperty((time) => {
		let m = Cesium.Transforms.computeIcrfToFixedMatrix(time);
		if (!m) m = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
		// 在ICRF中的标签位置（黄道面边缘外）
		const labelPosIcrf = new Cesium.Cartesian3(planeRadius * 1, planeRadius * 0.3, 0); // 调整位置避免重叠
		// 绕X轴旋转黄赤交角
		const obliquity = Cesium.Math.toRadians(23.439281);
		const cosE = Math.cos(obliquity);
		const sinE = Math.sin(obliquity);
		const yR = labelPosIcrf.y * cosE - labelPosIcrf.z * sinE;
		const zR = labelPosIcrf.y * sinE + labelPosIcrf.z * cosE;
		const labelPosEcliptic = new Cesium.Cartesian3(labelPosIcrf.x, yR, zR);
		// 转换到地固系
		return Cesium.Matrix3.multiplyByVector(m, labelPosEcliptic, new Cesium.Cartesian3());
	}, false);

	const eclipticLabel = entities.add({
		name: '黄道面标签',
		position: eclipticLabelPos,
		label: {
			text: '黄道面',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.WHITE, // 改为白色
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -20)
		}
	});
	referenceSystemEntities.value.push(eclipticLabel);
};

// 新增：创建春分点/秋分点轴（基于ICRF的±X方向，经当前时刻转换到地固系）
const createEquinoxAxes = (entities) => {
	const earthRadius = 6371000; // 地球半径 (米)
	const planeRadius = earthRadius * 5; // 与赤道面和黄道面相同的半径
	const axisLength = planeRadius; // 轴线长度调整为圆盘半径，使箭头到达交点
	const axisWidth = 1;
	const labelOffset = 500000;
	const arrowLength = 800000; // 箭头长度
	const arrowRadius = 200000; // 箭头底部半径

	const getDirFixed = (time) => {
		let m = Cesium.Transforms.computeIcrfToFixedMatrix(time);
		if (!m) m = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
		const xFixed = Cesium.Matrix3.multiplyByVector(m, new Cesium.Cartesian3(1, 0, 0), new Cesium.Cartesian3());
		return Cesium.Cartesian3.normalize(xFixed, xFixed);
	};

	const vernalPositions = new Cesium.CallbackProperty((time) => {
		const dir = getDirFixed(time);
		const start = Cesium.Cartesian3.multiplyByScalar(dir, 1, new Cesium.Cartesian3()); // 从地心附近开始，避免几何计算错误
		const end = Cesium.Cartesian3.multiplyByScalar(dir, axisLength, new Cesium.Cartesian3());
		return [start, end];
	}, false);

	const vernalLabelPos = new Cesium.CallbackProperty((time) => {
		const dir = getDirFixed(time);
		return Cesium.Cartesian3.multiplyByScalar(dir, axisLength + labelOffset, new Cesium.Cartesian3());
	}, false);

	const vernalArrowPos = new Cesium.CallbackProperty((time) => {
		const dir = getDirFixed(time);
		return Cesium.Cartesian3.multiplyByScalar(dir, axisLength - arrowLength / 2, new Cesium.Cartesian3());
	}, false);

	const vernalArrowOrientation = new Cesium.CallbackProperty((time) => {
		const dir = getDirFixed(time);
		const position = Cesium.Cartesian3.multiplyByScalar(dir, axisLength - arrowLength / 2, new Cesium.Cartesian3());
		return Cesium.Transforms.headingPitchRollQuaternion(position, new Cesium.HeadingPitchRoll(0, 0, 0));
	}, false);

	const vernalAxis = entities.add({
		name: '春分点轴',
		polyline: {
			positions: vernalPositions,
			width: axisWidth,
			material: Cesium.Color.GOLD.withAlpha(0.9),
			clampToGround: false
		}
	});
	referenceSystemEntities.value.push(vernalAxis);

	const vernalArrow = entities.add({
		name: '春分点轴箭头',
		position: vernalArrowPos,
		orientation: vernalArrowOrientation,
		cylinder: {
			length: arrowLength,
			topRadius: 0,
			bottomRadius: arrowRadius,
			material: Cesium.Color.GOLD.withAlpha(0.9)
		}
	});
	referenceSystemEntities.value.push(vernalArrow);

	const vernalLabel = entities.add({
		name: '春分点',
		position: vernalLabelPos,
		label: {
			text: '春分点',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.GOLD,
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -20)
		}
	});
	referenceSystemEntities.value.push(vernalLabel);

	const autumnalPositions = new Cesium.CallbackProperty((time) => {
		const dir = getDirFixed(time);
		const negDir = Cesium.Cartesian3.negate(dir, new Cesium.Cartesian3());
		const start = Cesium.Cartesian3.multiplyByScalar(negDir, 1, new Cesium.Cartesian3()); // 从地心附近开始，避免几何计算错误
		const end = Cesium.Cartesian3.multiplyByScalar(negDir, axisLength, new Cesium.Cartesian3());
		return [start, end];
	}, false);

	const autumnalLabelPos = new Cesium.CallbackProperty((time) => {
		const dir = getDirFixed(time);
		const negDir = Cesium.Cartesian3.negate(dir, new Cesium.Cartesian3());
		return Cesium.Cartesian3.multiplyByScalar(negDir, axisLength + labelOffset, new Cesium.Cartesian3());
	}, false);

	const autumnalArrowPos = new Cesium.CallbackProperty((time) => {
		const dir = getDirFixed(time);
		const negDir = Cesium.Cartesian3.negate(dir, new Cesium.Cartesian3());
		return Cesium.Cartesian3.multiplyByScalar(negDir, axisLength - arrowLength / 2, new Cesium.Cartesian3());
	}, false);

	const autumnalArrowOrientation = new Cesium.CallbackProperty((time) => {
		const dir = getDirFixed(time);
		const negDir = Cesium.Cartesian3.negate(dir, new Cesium.Cartesian3());
		const position = Cesium.Cartesian3.multiplyByScalar(negDir, axisLength - arrowLength / 2, new Cesium.Cartesian3());
		return Cesium.Transforms.headingPitchRollQuaternion(position, new Cesium.HeadingPitchRoll(0, 0, 0));
	}, false);

	const autumnalAxis = entities.add({
		name: '秋分点轴',
		polyline: {
			positions: autumnalPositions,
			width: axisWidth,
			material: Cesium.Color.CYAN.withAlpha(0.9),
			clampToGround: false
		}
	});
	referenceSystemEntities.value.push(autumnalAxis);

	const autumnalArrow = entities.add({
		name: '秋分点轴箭头',
		position: autumnalArrowPos,
		orientation: autumnalArrowOrientation,
		cylinder: {
			length: arrowLength,
			topRadius: 0,
			bottomRadius: arrowRadius,
			material: Cesium.Color.CYAN.withAlpha(0.9)
		}
	});
	referenceSystemEntities.value.push(autumnalArrow);

	const autumnalLabel = entities.add({
		name: '秋分点',
		position: autumnalLabelPos,
		label: {
			text: '秋分点',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.CYAN,
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -20)
		}
	});
	referenceSystemEntities.value.push(autumnalLabel);
};

// 创建轨道面
const createOrbitPlane = (entities) => {
	const earthRadius = 6371000; // 地球半径 (米)
	const planeRadius = earthRadius * 5; // 与赤道面和黄道面相同的半径

	// 获取轨道参数
	const params = currentOrbitParams;

	// 计算轨道面法向量（使用轨道倾角和升交点赤经）
	const inclination = Cesium.Math.toRadians(params.inclination);
	const raan = Cesium.Math.toRadians(params.raan);

	// 计算轨道平面的法向量
	// 使用与OrbitCalculator.js中orbitToInertial相同的计算方法
	const cosRaan = Math.cos(raan);
	const sinRaan = Math.sin(raan);
	const cosInc = Math.cos(inclination);
	const sinInc = Math.sin(inclination);

	// 轨道平面的法向量是轨道坐标系的z轴在惯性坐标系中的方向
	// 这对应于orbitToInertial变换矩阵的第三列
	const nx = sinRaan * sinInc;
	const ny = -cosRaan * sinInc;
	const nz = cosInc;
	const normal = new Cesium.Cartesian3(nx, ny, nz);
	Cesium.Cartesian3.normalize(normal, normal);

	// 找到与法向量垂直的两个向量作为平面基底
	let u = new Cesium.Cartesian3();
	if (Math.abs(normal.z) < 0.9) {
		u = Cesium.Cartesian3.cross(normal, Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3());
	} else {
		u = Cesium.Cartesian3.cross(normal, Cesium.Cartesian3.UNIT_X, new Cesium.Cartesian3());
	}
	Cesium.Cartesian3.normalize(u, u);

	const v = Cesium.Cartesian3.cross(normal, u, new Cesium.Cartesian3());
	Cesium.Cartesian3.normalize(v, v);

	// 生成圆形平面顶点 - 在ICRF坐标系中
	const segments = 180;
	const ringIcrf = [];
	for (let i = 0; i < segments; i++) {
		const angle = (i / segments) * Math.PI * 2;
		const x = planeRadius * Math.cos(angle);
		const y = planeRadius * Math.sin(angle);

		// 计算平面上的点 = 原点 + x*u + y*v
		const px = x * u.x + y * v.x;
		const py = x * u.y + y * v.y;
		const pz = x * u.z + y * v.z;

		ringIcrf.push(new Cesium.Cartesian3(px, py, pz));
	}

	// 创建从ICRF到FIXED的转换函数
	const transformRingToFixed = (time) => {
		let m = Cesium.Transforms.computeIcrfToFixedMatrix(time);
		if (!m) m = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
		const out = new Array(ringIcrf.length);
		for (let i = 0; i < ringIcrf.length; i++) {
			out[i] = Cesium.Matrix3.multiplyByVector(m, ringIcrf[i], new Cesium.Cartesian3());
		}
		return out;
	};

	// 使用CallbackProperty动态更新位置
	const hierarchyProperty = new Cesium.CallbackProperty((time) => {
		const positions = transformRingToFixed(time);
		return new Cesium.PolygonHierarchy(positions);
	}, false);

	const outlinePositionsProperty = new Cesium.CallbackProperty((time) => {
		const positions = transformRingToFixed(time);
		return [...positions, positions[0]];
	}, false);

	// 填充轨道平面
	const orbitPlaneFill = entities.add({
		name: '轨道平面',
		polygon: {
			hierarchy: hierarchyProperty,
			perPositionHeight: true,
			material: Cesium.Color.LIGHTCORAL.withAlpha(0.2) // 浅红色半透明
		}
	});
	referenceSystemEntities.value.push(orbitPlaneFill);

	// 轮廓圆环
	const orbitPlaneOutline = entities.add({
		name: '轨道平面轮廓',
		polyline: {
			positions: outlinePositionsProperty,
			width: 1,
			material: Cesium.Color.LIGHTCORAL.withAlpha(0.5), // 浅红色半透明
			clampToGround: false
		}
	});
	referenceSystemEntities.value.push(orbitPlaneOutline);

	// 添加轨道平面标签 - 使用CallbackProperty动态更新位置
	const labelPosition = new Cesium.CallbackProperty((time) => {
		let m = Cesium.Transforms.computeIcrfToFixedMatrix(time);
		if (!m) m = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);

		const labelPosIcrf = new Cesium.Cartesian3(
			planeRadius * 1.1 * u.x,
			planeRadius * 1.1 * u.y,
			planeRadius * 1.1 * u.z
		);
		return Cesium.Matrix3.multiplyByVector(m, labelPosIcrf, new Cesium.Cartesian3());
	}, false);

	const orbitPlaneLabel = entities.add({
		name: '轨道平面标签',
		position: labelPosition,
		label: {
			text: '轨道平面',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.WHITE,
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -20)
		}
	});
	referenceSystemEntities.value.push(orbitPlaneLabel);
};

// 创建天球
const createCelestialSphere = (entities) => {
	const earthRadius = 6371000; // 地球半径 (米)
	const sphereRadius = earthRadius * 5; // 与赤道面相同的半径

	const celestialSphere = entities.add({
		name: '天球',
		position: Cesium.Cartesian3.ZERO, // 以地心为中心
		ellipsoid: {
			radii: new Cesium.Cartesian3(sphereRadius, sphereRadius, sphereRadius),
			material: Cesium.Color.LIGHTBLUE.withAlpha(0.1), // 淡蓝色，半透明
			outline: false,
			fill: true
		}
	});
	referenceSystemEntities.value.push(celestialSphere);
};

// 创建太阳在黄道面的投影
const createSunProjection = (entities) => {
	const earthRadius = 6371000; // 地球半径 (米)
	const planeRadius = earthRadius * 5; // 黄道面半径

	// 计算太阳在黄道面上的投影位置
	const sunProjectionPosition = new Cesium.CallbackProperty((time) => {
		// 获取太阳在ICRF惯性系中的方向
		const sunDirection = Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(time);
		if (!sunDirection) {
			return Cesium.Cartesian3.ZERO;
		}

		// 将太阳方向归一化并放置在合适的距离
		const normalizedSunDir = Cesium.Cartesian3.normalize(sunDirection, new Cesium.Cartesian3());
		const sunPositionIcrf = Cesium.Cartesian3.multiplyByScalar(normalizedSunDir, planeRadius, new Cesium.Cartesian3());

		// 将ICRF坐标转换到地固系
		let transformMatrix = Cesium.Transforms.computeIcrfToFixedMatrix(time);
		if (!transformMatrix) {
			transformMatrix = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
		}

		const sunPositionFixed = Cesium.Matrix3.multiplyByVector(transformMatrix, sunPositionIcrf, new Cesium.Cartesian3());
		return sunPositionFixed;
	}, false);

	const sunProjection = entities.add({
		name: '太阳投影',
		position: sunProjectionPosition,
		point: {
			pixelSize: 8,
			color: Cesium.Color.RED,
			outlineColor: Cesium.Color.DARKRED,
			outlineWidth: 2,
			heightReference: Cesium.HeightReference.NONE
		},
		label: {
			text: '太阳投影',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.YELLOW,
			outlineColor: Cesium.Color.BLACK,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(10, -10)
		}
	});
	referenceSystemEntities.value.push(sunProjection);
};

// 计算近地点和远地点位置
const calculateApsisPositions = (params) => {
	console.log('计算近地点和远地点位置', params);
	const semiMajorAxis = params.semiMajorAxis * 1000; // 转换为米
	const eccentricity = params.eccentricity;
	const inclination = Cesium.Math.toRadians(params.inclination);
	const raan = Cesium.Math.toRadians(params.raan); // 升交点赤经
	const argOfPerigee = Cesium.Math.toRadians(params.argumentOfPerigee); // 近地点幅角（修正属性名）

	// 计算近地点和远地点距离
	const perigeeDistance = semiMajorAxis * (1 - eccentricity);
	const apogeeDistance = semiMajorAxis * (1 + eccentricity);

	// 在轨道坐标系中的近地点和远地点位置
	const perigeeOrbit = new Cesium.Cartesian3(perigeeDistance, 0, 0); // +X方向为近地点
	const apogeeOrbit = new Cesium.Cartesian3(-apogeeDistance, 0, 0); // -X方向为远地点

	// 创建旋转矩阵：先绕Z轴旋转近地点幅角，再绕X轴旋转倾角，最后绕Z轴旋转升交点赤经
	const rotationMatrix = new Cesium.Matrix3();
	const tempMatrix1 = new Cesium.Matrix3();
	const tempMatrix2 = new Cesium.Matrix3();
	const tempMatrix3 = new Cesium.Matrix3();

	// 1. 绕Z轴旋转近地点幅角
	Cesium.Matrix3.fromRotationZ(argOfPerigee, tempMatrix1);
	// 2. 绕X轴旋转倾角
	Cesium.Matrix3.fromRotationX(inclination, tempMatrix2);
	// 3. 绕Z轴旋转升交点赤经
	Cesium.Matrix3.fromRotationZ(raan, tempMatrix3);

	// 组合旋转矩阵
	Cesium.Matrix3.multiply(tempMatrix2, tempMatrix1, rotationMatrix);
	Cesium.Matrix3.multiply(tempMatrix3, rotationMatrix, rotationMatrix);

	// 将轨道坐标系中的位置转换到地心坐标系
	const perigeeECI = new Cesium.Cartesian3();
	const apogeeECI = new Cesium.Cartesian3();
	Cesium.Matrix3.multiplyByVector(rotationMatrix, perigeeOrbit, perigeeECI);
	Cesium.Matrix3.multiplyByVector(rotationMatrix, apogeeOrbit, apogeeECI);

	return { perigeeECI, apogeeECI };
};

// 在预测轨道上添加近地点和远地点标记
const addApsisPoints = (params) => {
	if (!props.cesiumViewer) return;

	const { perigeeECI, apogeeECI } = calculateApsisPositions(params);

	// 创建近地点和远地点之间的连线
	const apsisLine = props.cesiumViewer.entities.add({
		name: '近地点-远地点连线',
		polyline: {
			positions: new Cesium.CallbackProperty((time) => {
				const icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
				if (icrfToFixed) {
					const perFixed = Cesium.Matrix3.multiplyByVector(icrfToFixed, perigeeECI, new Cesium.Cartesian3());
					const apoFixed = Cesium.Matrix3.multiplyByVector(icrfToFixed, apogeeECI, new Cesium.Cartesian3());
					return [perFixed, apoFixed];
				}
				// 兜底：直接返回原值（可能会有微小误差）
				return [perigeeECI, apogeeECI];
			}, false),
			width: 1,
			material: Cesium.Color.YELLOW,
			clampToGround: false,
			heightReference: Cesium.HeightReference.NONE,
			arcType: Cesium.ArcType.NONE,
			granularity: Cesium.Math.RADIANS_PER_DEGREE // 显式设置粒度，避免过小导致报错
		}
	});

	// 添加近地点标记
	// 使用圆锥箭头（CylinderGraphics，topRadius为0）替代原先的点标记
	const arrowLength = 400000; // 箭头长度（米）
	const arrowRadius = 120000; // 箭头底部半径（米）
	const baseClearance = 5000; // 为避免箭头在近/远地点处“长出来”，在底部留出5km的余量

	// 计算箭头实体应当放置的中心点（CylinderGraphics 以中心为锚点）
	// 将中心沿径向外偏移 length/2 + baseClearance，使底部略微离开近/远地点，避免反向伸出
	const perigeeCenterECI = Cesium.Cartesian3.add(
		perigeeECI,
		Cesium.Cartesian3.multiplyByScalar(
			Cesium.Cartesian3.normalize(perigeeECI, new Cesium.Cartesian3()),
			arrowLength / 2 - arrowLength,
			new Cesium.Cartesian3()
		),
		new Cesium.Cartesian3()
	);
	const apogeeCenterECI = Cesium.Cartesian3.add(
		apogeeECI,
		Cesium.Cartesian3.multiplyByScalar(
			Cesium.Cartesian3.normalize(apogeeECI, new Cesium.Cartesian3()),
			arrowLength / 2 - arrowLength,
			new Cesium.Cartesian3()
		),
		new Cesium.Cartesian3()
	);

	// 动态计算近地点箭头的朝向：指向径向外（与坐标轴箭头一致）
	const perigeeOrientation = new Cesium.CallbackProperty((time) => {
		const icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
		let perigeeFixed = perigeeCenterECI;
		if (Cesium.defined(icrfToFixed)) {
			perigeeFixed = Cesium.Matrix3.multiplyByVector(icrfToFixed, perigeeCenterECI, new Cesium.Cartesian3());
		}
		return Cesium.Transforms.headingPitchRollQuaternion(perigeeFixed, new Cesium.HeadingPitchRoll(0, 0, 0));
	}, false);

	const perigeePoint = props.cesiumViewer.entities.add({
		name: '近地点',
		position: new Cesium.ConstantPositionProperty(perigeeCenterECI, Cesium.ReferenceFrame.INERTIAL),
		orientation: perigeeOrientation,
		cylinder: {
			length: arrowLength,
			topRadius: 0,
			bottomRadius: arrowRadius,
			material: Cesium.Color.YELLOW.withAlpha(0.95)
		},
		label: {
			text: '近地点',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.YELLOW,
			outlineColor: Cesium.Color.YELLOW,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -50),
			show: true,
			disableDepthTestDistance: Number.POSITIVE_INFINITY
		}
	});

	// 添加远地点标记
	// 动态计算远地点箭头的朝向：指向径向外（与坐标轴箭头一致）
	const apogeeOrientation = new Cesium.CallbackProperty((time) => {
		const icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
		let apogeeFixed = apogeeCenterECI;
		if (Cesium.defined(icrfToFixed)) {
			apogeeFixed = Cesium.Matrix3.multiplyByVector(icrfToFixed, apogeeCenterECI, new Cesium.Cartesian3());
		}
		return Cesium.Transforms.headingPitchRollQuaternion(apogeeFixed, new Cesium.HeadingPitchRoll(0, 0, 0));
	}, false);

	const apogeePoint = props.cesiumViewer.entities.add({
		name: '远地点',
		position: new Cesium.ConstantPositionProperty(apogeeCenterECI, Cesium.ReferenceFrame.INERTIAL),
		orientation: apogeeOrientation,
		cylinder: {
			length: arrowLength,
			topRadius: 0,
			bottomRadius: arrowRadius,
			material: Cesium.Color.YELLOW.withAlpha(0.95)
		},
		label: {
			text: '远地点',
			font: '12pt sans-serif',
			fillColor: Cesium.Color.YELLOW,
			outlineColor: Cesium.Color.YELLOW,
			outlineWidth: 1,
			style: Cesium.LabelStyle.FILL_AND_OUTLINE,
			pixelOffset: new Cesium.Cartesian2(0, -50),
			show: true,
			disableDepthTestDistance: Number.POSITIVE_INFINITY
		}
	});

	// 将近地点和远地点标记添加到预览轨道实体中，以便在移除轨道时一并移除
	if (previewOrbitEntity.value) {
		previewOrbitEntity.value.perigeePoint = perigeePoint;
		previewOrbitEntity.value.apogeePoint = apogeePoint;
		previewOrbitEntity.value.apsisLine = apsisLine;
	}
};

// 创建近地点远地点连线
const createApsisLine = (entities) => {
	const { perigeeECI, apogeeECI } = calculateApsisPositions(currentOrbitParams);

	// 创建近地点远地点连线
	const apsisLine = entities.add({
		name: '近地点-远地点连线',
		polyline: {
			positions: [perigeeECI, apogeeECI],
			width: 1,
			material: Cesium.Color.ORANGE.withAlpha(0.9),
			clampToGround: false,
			heightReference: Cesium.HeightReference.NONE,
			arcType: Cesium.ArcType.NONE,
			granularity: Cesium.Math.RADIANS_PER_DEGREE // 显式设置粒度，避免过小导致报错
		}
	});
	referenceSystemEntities.value.push(apsisLine);
};

// 使用内置栅格图层显示经纬度网格
const createLatLonGridLayer = () => {
	if (!props.cesiumViewer) return;

	// 若已存在则先移除，避免重复叠加
	if (latLonGridLayer.value) {
		props.cesiumViewer.imageryLayers.remove(latLonGridLayer.value, false);
		latLonGridLayer.value = null;
	}

	const provider = new Cesium.GridImageryProvider({
		tilingScheme: new Cesium.GeographicTilingScheme(),
		cells: 8, // 每个影像瓦片内的格数，随缩放级别自动细分
		color: Cesium.Color.WHITE.withAlpha(0.25),
		glowColor: Cesium.Color.WHITE.withAlpha(0.05),
		glowWidth: 1.0,
		backgroundColor: Cesium.Color.TRANSPARENT
	});
	latLonGridLayer.value = props.cesiumViewer.imageryLayers.addImageryProvider(provider);
	// 置顶保证经纬网位于最上层
	props.cesiumViewer.imageryLayers.raiseToTop(latLonGridLayer.value);
};

// 移除坐标系
const removeReferenceSystem = () => {
	if (!props.cesiumViewer) return;

	// 移除实体
	referenceSystemEntities.value.forEach((entity) => {
		props.cesiumViewer.entities.remove(entity);
	});
	referenceSystemEntities.value = [];

	// 移除经纬网图层
	if (latLonGridLayer.value) {
		props.cesiumViewer.imageryLayers.remove(latLonGridLayer.value, false);
		latLonGridLayer.value = null;
	}
};

// 格式化时间
const formatTime = (seconds) => {
	const hours = Math.floor(seconds / 3600);
	const minutes = Math.floor((seconds % 3600) / 60);
	const secs = Math.floor(seconds % 60);
	return `${hours}h ${minutes}m ${secs}s`;
};

// 组件挂载时自动显示轨道
onMounted(() => {
	if (enablePreview.value) {
		handleRealTimeUpdate(currentOrbitParams);
	}
});

// 组件卸载时清理预览轨道和坐标系
onUnmounted(() => {
	if (previewOrbitEntity.value && props.cesiumViewer) {
		props.cesiumViewer.entities.remove(previewOrbitEntity.value);
		previewOrbitEntity.value = null;
	}
	// 清理坐标系
	removeReferenceSystem();
});
</script>

<style scoped>
.orbit-designer {
	padding: 16px;
	height: 100%;
	overflow-y: auto;
	display: flex;
	flex-direction: column;
}

.orbit-designer-header {
	margin-bottom: 16px;
	padding-bottom: 12px;
	border-bottom: 1px solid #ebeef5;
}

.description {
	margin: 0;
	color: #606266;
	font-size: 14px;
	line-height: 1.4;
}

.orbit-designer-content {
	display: flex;
	flex-direction: column;
	gap: 16px;
	flex: 1;
	min-height: 0;
}

.parameters-section {
	background: #f8f9fa;
	border-radius: 6px;
	padding: 12px;
}

.preview-controls {
	display: flex;
	align-items: center;
	gap: 12px;
	margin-bottom: 12px;
	padding: 8px 12px;
	background: #fff;
	border-radius: 4px;
	border: 1px solid #e4e7ed;
}

.preview-status {
	display: flex;
	align-items: center;
	gap: 4px;
	color: #67c23a;
	font-size: 13px;
}

.orbit-info-section {
	background: #fff;
	border: 1px solid #ebeef5;
	border-radius: 6px;
	padding: 12px;
}

.orbit-info-card h4 {
	margin: 0 0 12px 0;
	color: #303133;
	font-size: 16px;
	font-weight: 600;
}

.info-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 12px;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8px 12px;
	background: #f5f7fa;
	border-radius: 4px;
}

.info-item .label {
	color: #606266;
	font-size: 13px;
}

.info-item .value {
	color: #303133;
	font-weight: 500;
	font-size: 13px;
}
</style>
